package atom.core2.j2ee.servlet;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.PropertyConfigurator;
import org.apache.log4j.xml.DOMConfigurator;

import atom.core0.global.GlobalCache;
import atom.core0.util.StringUtil;
import atom.core2.j2ee.util.ServletUtil;

public class InitLog4jServlet extends HttpServlet
{
	private static final long	serialVersionUID	= 1L;

	public void init() throws ServletException
	{
		super.init();
		String file = getInitParameter("log4j");

		String log4jpath = GlobalCache.getSystemCache("log4jpath");
		if (StringUtil.isEmpty(log4jpath))
			log4jpath = "";
		// 陈亮 如果是相对路径   /开始的  D:盘符的不替换
		if (!log4jpath.startsWith("/"))
		{
			if (log4jpath.indexOf(":") <= 0)
			{
				log4jpath = "/home/" + System.getProperty("user.name") + "/" + log4jpath;
			}
		}
		//

		System.setProperty("log4jpath", log4jpath);
		if (StringUtils.isEmpty(file))
		{
			return;
		}

		try
		{
			if (file.endsWith(".xml"))
			{
				// Log4jServlet.class.
				String path = ServletUtil.getServletContext().getRealPath("");
				System.out.println("log4jfilepath=" + path + file);
				DOMConfigurator.configureAndWatch(path + file);
			}
			else
			{
				Properties ps = new Properties();
				ps.load(getServletContext().getResourceAsStream(file));
				PropertyConfigurator.configure(ps);

				// PropertyConfigurator.configureAndWatch(file,1000);//
				// 间隔特定时间，检测文件是否修改，自动重新读取配置
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
